<template>
  <div class="app-container">
    <!-- 条件搜索 -->
    <div class="filter-container">
      <el-form ref="queryForm" :model="listQuery" size="small" :inline="true" label-width="auto">
        <el-form-item label="组织名称" prop="orgId">
          <ft-org-select v-model="listQuery.orgId" :placeholder="'组织名称'" :multiple="false" :default-expand-level="2" />
        </el-form-item>
        <el-form-item label="使用状态" prop="status">
          <el-select v-model="listQuery.status" placeholder="使用状态" style="width: 150px;" class="filter-item" @change="handleFilterQuery">
            <el-option v-for="item in statusOptions" :key="item.code" :label="item.text" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 10px;" @click="handleFilterQuery">
          搜索
        </el-button>
        <el-button v-waves class="filter-item" icon="el-icon-refresh-right" @click="handleRestQuery">
          重置
        </el-button>
      </el-form>
    </div>

    <!-- 表格操作工具栏 -->
    <div class="filter-container">
      <div style="float: left;">
        <el-button v-permission="permission.add" class="filter-item" type="primary" plain icon="el-icon-plus" @click="handleCreate">
          新增
        </el-button>
        <el-button class="filter-item" type="primary" plain icon="el-icon-sort" @click="handleExpand">
          展开/折叠
        </el-button>
      </div>
      <div style="float: right;">
        <el-button icon="el-icon-refresh" circle @click="handleFilterQuery" />
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      ref="treeTable"
      :key="tableKey"
      v-loading="loading"
      row-key="orgId"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      scrollbar-always-on="true"
      :default-expand-all="expandAll"
      :expand-row-keys="expandRowKeys"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="序号" type="index" width="50px" align="center" />
      <el-table-column label="组织名称" min-width="180px" align="left">
        <template v-slot="{row}">
          <span>{{ row.orgName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="组织编码" min-width="80px" align="left">
        <template v-slot="{row}">
          <span>{{ row.orgId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="组织类型" align="left" min-width="70px">
        <template v-slot="{row}">
          <el-tag v-if="row.orgType === 'org'" effect="dark">机构</el-tag>
          <el-tag v-else effect="dark" type="success">部门</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="组织层级" align="left" min-width="70px">
        <template v-slot="{row}">
          <el-tag v-if="row.orgLevel === '01'">一级组织</el-tag>
          <el-tag v-else-if="row.orgLevel === '02'" type="success">二级组织</el-tag>
          <el-tag v-else-if="row.orgLevel === '03'" type="info">三级级组织</el-tag>
          <span v-else />
        </template>
      </el-table-column>
      <el-table-column label="办公电话" min-width="80px" align="left">
        <template v-slot="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地址" min-width="120px" align="left">
        <template v-slot="{row}">
          <span>{{ row.orgAddress }}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用状态" class-name="status-col" width="70px">
        <template v-slot="{row}">
          <el-switch :value="row.status ==='Y'" disabled />
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="80px" align="left">
        <template v-slot="{row}">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" min-width="70px" align="left">
        <template v-slot="{row}">
          <span>{{ row.updatedBy }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="160px" align="left">
        <template v-slot="{row}">
          <span>{{ row.updatedTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="160px" class-name="small-padding fixed-width">
        <template v-slot="{row,$index}">
          <el-button size="mini" type="info" icon="el-icon-document" @click="handleDetail(row, $index)">详情</el-button>
          <el-dropdown style="margin-left: 10px;" @command="handleClick($event, row, $index)">
            <el-button size="mini" type="primary">更多
              <i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu>
              <el-dropdown-item v-permission="permission.edit" command="edit"><i class="el-icon-edit"> 编辑</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.del" command="del"><i class="el-icon-delete"> 删除</i></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑页面 -->
    <el-dialog :title="title[state]" :visible.sync="visible" :close-on-click-modal="false" width="800px" @close="handleClose">
      <el-form ref="dataForm" :rules="rules" :model="formData" label-position="right" label-width="100px">
        <el-input v-model="formData.id" type="hidden" />
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级组织" prop="parentId">
              <ft-org-select v-model="formData.parentId" width="100%" :default-expand-level="1" :disabled="state==='detail'" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="组织名称" prop="orgName">
              <el-input v-model="formData.orgName" :readonly="state==='detail'" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织编码" prop="orgId">
              <el-input v-model="formData.orgId" readonly placeholder="系统自动生成" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="组织类型" prop="orgType">
              <el-radio v-model="formData.orgType" :disabled="state==='detail'" label="org">机构</el-radio>
              <el-radio v-model="formData.orgType" :disabled="state==='detail'" label="dept">部门</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="组织层级" prop="orgLevel">
              <el-select v-model="formData.orgLevel" :disabled="state==='detail'" class="filter-item" style="width: 100%;" placeholder="请选择" clearable>
                <el-option v-for="item in orgLevelOptions" :key="item.code" :label="item.text" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="机构路径" prop="orgPath">
              <el-input v-model="formData.orgPath" :readonly="state==='detail'" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="办公电话" prop="phone">
              <el-input v-model="formData.phone" :readonly="state==='detail'" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="所在地址" prop="orgAddress">
              <el-input v-model="formData.orgAddress" :readonly="state==='detail'" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="使用状态" prop="status">
              <el-radio v-model="formData.status" :disabled="state==='detail'" label="Y">启用</el-radio>
              <el-radio v-model="formData.status" :disabled="state==='detail'" label="N">禁用</el-radio>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" :readonly="state==='detail'" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="handleClose">
          取消
        </el-button>
        <el-button v-if="state !=='detail'" :loading="submitting" type="primary" icon="el-icon-check" @click="handleSubmitFormData">
          <span v-if="!submitting">确认</span>
          <span v-else>提 交 中...</span>
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPageList, handleSave, handleDelete, getAllOrgList } from './api'
import permission from '@/directive/permission/index' // 权限判断指令
// import checkPermission from '@/utils/permission' // 权限判断函数
import waves from '@/directive/waves' // waves directive
// import { parseTime } from '@/utils'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import FtOrgSelect from '@/views/components/FtOrgSelect/index.vue'

export default {
  name: 'OrgInfo',
  components: { FtOrgSelect },
  directives: { permission, waves },
  filters: {},
  data() {
    return {
      // 列表table的key
      tableKey: 0,
      // 遮罩层
      loading: true,
      // table数据对象
      list: [],
      // TreeTable 是否展开属性
      expandAll: false,
      // 展开节点
      expandRowKeys: [],
      // table条件查询对象
      listQuery: {
        orgId: undefined,
        status: undefined
      },
      // 状态字典
      statusOptions: [{ code: 'Y', text: '启用' }, { code: 'N', text: '禁用' }],
      orgLevelOptions: [{ code: '01', text: '一级组织' }, { code: '02', text: '二级组织' }, { code: '03', text: '三级组织' }],
      // 表单数据对象
      formData: {},
      // 树形下拉选项
      orgSelectOptions: [],
      // 是否显示弹出层
      visible: false,
      // 弹出层状态值
      state: '',
      // 弹出层标题
      title: {
        update: '修改',
        create: '新增',
        detail: '详情'
      },
      // 权限标识
      permission: {
        add: ['sys:org:add'],
        edit: ['sys:org:edit'],
        del: ['sys:org:del']
      },
      submitting: false,
      // 表单校验规则
      rules: {
        parentId: [{ required: true, message: '上级不能为空', trigger: 'change' }],
        orgName: [{ required: true, message: '组织名称不能为空', trigger: 'change' }],
        orgType: [{ required: true, message: '所属类型不能为空', trigger: 'change' }],
        orgLevel: [{ required: true, message: '所属层级不能为空', trigger: 'change' }],
        phone: [{ required: true, message: '办公电话不能为空', trigger: 'change' }],
        orgAddress: [{ required: true, message: '所属地址不能为空', trigger: 'change' }]
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    this.handleInit()
    this.handleRestFormData()

    getAllOrgList().then(res => {
      this.orgSelectOptions = res.data
    })
  },
  mounted() {},
  methods: {
    // 查询table数据对象
    handleInit() {
      this.loading = true
      getPageList(this.listQuery).then(res => {
        this.list = res.data
        this.list.forEach(e => {
          if (e.orgLevel === '00' || e.orgLevel === '01') {
            this.expandRowKeys.push(e.orgId)
          }
        })
        this.loading = false
      })
    },
    // 条件查询table数据
    handleFilterQuery() {
      this.handleInit()
    },
    // 重置table查询条件
    handleRestQuery() {
      this.$refs.queryForm.resetFields()
      this.handleInit()
    },
    // 重置表单
    handleRestFormData() {
      this.formData = {
        id: undefined,
        orgId: undefined,
        orgName: undefined,
        parentId: undefined,
        parentName: undefined,
        orgLevel: undefined,
        orgType: 'org',
        orgPath: undefined,
        phone: undefined,
        orgAddress: undefined,
        status: 'Y',
        remark: ''
      }
    },
    // 更多点击操作项
    handleClick(item, row, index) {
      // 编辑
      if (item === 'edit') {
        this.handleUpdate(row, index)
      }
      // 删除
      if (item === 'del') {
        this.handleDelete(row, index)
      }
    },
    // 新增
    handleCreate() {
      this.state = 'create'
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 修改
    handleUpdate(row) {
      if (row.parentId === 'root') {
        this.$message({
          showClose: true,
          message: '根目录资源不允许修改！',
          type: 'warning',
          duration: 4000
        })
        return
      }
      this.state = 'update'
      this.visible = true
      // 创建一个新的对象赋值
      this.formData = Object.assign({}, row)
      // 清理没有用的属性，避免数据不对问题
      delete this.formData.createdBy
      delete this.formData.createdTime
      delete this.formData.updatedBy
      delete this.formData.updatedTime
      delete this.formData.tenantId
      delete this.formData.revision
      delete this.formData.deleted

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 详情
    handleDetail(row) {
      this.state = 'detail'
      this.visible = true
      // 创建一个新的对象赋值
      this.formData = Object.assign({}, row)

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 删除
    handleDelete(row, index) {
      if (row.parentId === 'root') {
        this.$message({
          showClose: true,
          message: '根目录资源不允许删除！',
          type: 'warning',
          duration: 4000
        })
        return
      }
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 显示加载遮罩
        const loading = this.$loading({ lock: true, text: '处理中...', body: true, fullscreen: false, background: 'rgba(0, 0, 0, 0.05)' })
        handleDelete({ orgId: row.orgId }).then((res) => {
          loading.close()
          //  刷新table
          this.handleFilterQuery()
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'success',
            duration: 4000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 表单提交
    handleSubmitFormData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.submitting = true
          handleSave(this.formData).then((res) => {
            this.submitting = false
            //  刷新table
            this.handleFilterQuery()
            this.handleClose()
            this.$message({
              showClose: true,
              message: res.msg,
              type: 'success',
              duration: 4000
            })
          })
        }
      })
    },
    // 字段默认 id label 用于规范化数据源
    handleTreeSelectNormalizer(node) {
      if (!node.children || !node.children.length) {
        delete node.children
      }
      return node
    },
    // 全部展开TreeTable
    handleExpand() {
      this.expandAll = !this.expandAll
      this.toggleRowExpansion_forAll(this.list, this.expandAll)
    },
    // 触发循环展开子节点
    toggleRowExpansion_forAll(data, isExpansion) {
      data.forEach(item => {
        this.$refs.treeTable.toggleRowExpansion(item, isExpansion)
        if (item.children !== undefined && item.children !== null) {
          this.toggleRowExpansion_forAll(item.children, isExpansion)
        }
      })
    },
    // 关闭弹出层
    handleClose() {
      this.$refs['dataForm'].resetFields()
      this.handleRestFormData()
      this.visible = false
    }
  }
}
</script>
<style>
.vue-treeselect__control{
  height: 32px;
}
.el-input.is-disabled .el-input__inner {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-radio.is-disabled .el-radio__inner {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-radio__input.is-disabled {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-radio__input.is-disabled.is-checked {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-radio__label {
  background-color: #ffffff !important;
  cursor: pointer !important;
}
.el-textarea.is-disabled .el-textarea__inner {
  background-color: #ffffff !important;
}
.vue-treeselect--disabled .vue-treeselect__control {
  background-color: #ffffff !important;
}
</style>
